<template>
  <div id="container"></div>
</template>
<script>
import {
  defineComponent,
  onBeforeMount,
  onMounted,
  reactive,
  toRefs,
} from "vue";
import * as THREE from "three";
let scene, line;
export default defineComponent({
  setup() {
    const state = reactive({
      renderer: "",
      requestID: "",
      point: "",
    });
    onMounted(() => {
      init();
    });
    onBeforeMount(() => {
      // 页面跳转的时候停止RAF
      window.cancelAnimationFrame(state.requestID);
    });
    // 创建相机
    const initCamera = () => {
      // 创建相机
      state.camera = new THREE.PerspectiveCamera(
        75,
        window.innerWidth / window.innerHeight,
        0.1,
        1000
      );
      state.camera.position.z = 5;
      state.camera.position.x = 0;
    };
    // 创建渲染器
    const initRenderer = () => {
      state.renderer = new THREE.WebGLRenderer();
      state.renderer.setSize(window.innerWidth, window.innerHeight);
      let container = document.getElementById("container");
      state.renderer.setClearColor(0xb9d3ff, 1);
      container.appendChild(state.renderer.domElement);
    };
    // 执行动画
    const animate = () => {
      state.requestID = requestAnimationFrame(animate);
      render();
    };

    // 具体用来调用的动画
    const render = () => {
      line.rotation.x += 0.01;
      line.rotation.y += 0.01;
      state.renderer.render(scene, state.camera);
    };
    const loadGeometry = () => {
      var geometry = new THREE.SphereGeometry(100, 25, 25); //球体
      // 直线基础材质对象
      var material = new THREE.LineBasicMaterial({
        color: 0x0000ff,
      });
      line = new THREE.Line(geometry, material);
      scene.add(line);
      state.renderer.render(scene, state.camera);
    };
    // 光源设置
    const initLight = () => {
      state.point = new THREE.PointLight(0xffffff);
      state.point.position.set(400, 200, 300); //点光源位置
      var ambient = new THREE.AmbientLight(0x444444);
      scene.add(ambient);
    };
    const init = () => {
      //加载场景
      scene = new THREE.Scene();
      // 加载相机
      initCamera();
      // 加载渲染器
      initRenderer();
      // 加载物体材质
      loadGeometry();
      initLight();
      animate();
    };
    return {
      ...toRefs(state),
    };
  },
});
</script>
